<template>
  <view class="auth-page">
    <image class="page-bg" src="/static/images/bg.png" mode="aspectFill" />
    <view class="gradient-bg" :style="{ top: navBarHeight + 'px' }"></view>
    <CustomNavbar title="身份验证" />
    
    <view class="page-content" :style="{ paddingTop: navBarHeight + 'px' }">
      <!-- 白色卡片容器 -->
      <view class="form-card">
        <!-- 手机号 -->
        <view class="form-item">
          <text class="form-label">手机号</text>
          <input 
            class="form-input" 
            type="text" 
            :value="phoneNumber"
            disabled
          />
        </view>
        
        <!-- 姓名 -->
        <view class="form-item">
          <text class="form-label">姓名</text>
          <input 
            class="form-input" 
            type="text" 
            placeholder="请输入"
            v-model="name"
            maxlength="20"
          />
        </view>
        
        <!-- 身份证 -->
        <view class="form-item">
          <text class="form-label">身份证</text>
          <input 
            class="form-input" 
            type="text" 
            placeholder="请输入"
            v-model="idCard"
            maxlength="18"
          />
        </view>
        
        <!-- 图形验证码 -->
        <view class="form-item">
          <text class="form-label">图形验证码</text>
          <view class="form-input-wrapper">
            <input 
              class="form-input captcha-input" 
              type="text" 
              placeholder="请输入"
              v-model="captchaCode"
              maxlength="6"
            />
            <view class="captcha-image-wrapper" @click="refreshCaptcha">
              <!-- <text class="captcha-text">{{ captchaText }}</text> -->
               <image :src="flowPic" class="captcha-image" style="width: 100px; height: 38px;" />
            </view>
          </view>
        </view>
        
        <!-- 短信验证码 -->
        <view class="form-item">
          <text class="form-label">短信验证码</text>
          <view class="form-input-wrapper">
            <input 
              class="form-input sms-input" 
              type="text" 
              placeholder="请输入"
              v-model="smsCode"
              maxlength="6"
            />
            <button 
              class="sms-btn" 
              :disabled="smsDisabled"
              @click="sendSmsCode"
            >
              {{ smsBtnText }}
            </button>
          </view>
        </view>
      </view>
      
      <!-- 提示文字 -->
       <view class="form-tip">
        <view class="tip-text">
            <text>身份验证通过后30分钟内有效</text>
          </view>
          
          <!-- 查询按钮 -->
          <button class="query-btn" @click="handleQuery">查询</button>
       </view>
      
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import CustomNavbar from '@/components/CustomNavbar.vue'
import { api } from '@/utils/api.js'

const flowPic = ref('')



const navBarHeight = ref(80)
const phoneNumber = ref('189****0691')
const name = ref('')
const idCard = ref('')
const captchaCode = ref('')
const smsCode = ref('')
const captchaText = ref('') // 图形验证码文本
const smsDisabled = ref(false)
const smsBtnText = ref('获取验证码')
const queryParams = ref(null) // 存储查询参数
let smsCountdown = 60
let smsTimer = null

// 页面加载时接收参数
onLoad((options) => {
  if (options && options.queryParams) {
    try {
      queryParams.value = JSON.parse(decodeURIComponent(options.queryParams))
      // 如果有手机号参数，更新显示
      if (queryParams.value.phoneNumber) {
        phoneNumber.value = queryParams.value.phoneNumber
      }
      console.log('接收到的查询参数:', queryParams.value)
    } catch (e) {
      console.error('解析查询参数失败:', e)
    }
  }

  
})

onMounted(() => {
  const windowInfo = uni.getWindowInfo()
  const statusBarHeight = windowInfo.statusBarHeight || 0
  navBarHeight.value = statusBarHeight + 44
  



  // 初始化图形验证码
  refreshCaptcha()
})
// {"userName": userName,"idCardNum":idCardNum,
// "imgCheckCode":imgCheckCode,"smsCheckCode":smsCheckCode}
const userIDCheck = () =>{
  api.userIDCheck({
    // phone: phoneNumber.value,
    userName: name.value,
    idCardNum: idCard.value,
    imgCheckCode: captchaCode.value,
    smsCheckCode: smsCode.value
  }).then(res => {
    const data = res.data
    console.log('身份验证:', JSON.stringify(data))
    if (data.code === 200) {
      uni.showToast({
        title: '身份验证成功',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: data.msg || '身份验证失败',
        icon: 'none'
      })
    }
  }).catch(err => {
    console.error('身份验证失败:', err)
    uni.showToast({
      title: '身份验证失败，请稍后重试',
      icon: 'none'
    })
  })
}

const sendUserCheckSmsCode  = () =>{
  api.sendUserCheckSmsCode({
    phone: phoneNumber.value,
  }).then(res => {
    // const data = res.data
    console.log('发送详单用户发送短信:', JSON.stringify(res))
    if (res.code === 200) {
      uni.showToast({
        title: '发送短信验证码成功',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: data.msg || '发送短信验证码失败',
        icon: 'none'
      })
    }
  }).catch(err => {
    console.error('发送详单用户发送短信失败:', err)
    uni.showToast({
      title: '发送短信验证码失败，请稍后重试',
      icon: 'none'
    })
  })
}

// 生成随机验证码文本
const generateCaptchaText = () => {
  // 生成4位随机字符（数字+字母）
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
  let text = ''
  for (let i = 0; i < 4; i++) {
    text += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return text
}

const getImgCheckCode = () =>{
  api.getImgCheckCode({
    // wxphone: wx.getStorageSync('wxphone'),
  }).then(res => {
    const data = res.data
    console.log('获取图形验证码1111:', res)
    // var url = window.URL.createObjectURL(res)
    
        var url =  'data:image/png;base64,'+uni.arrayBufferToBase64(res);
    console.log('1111111:', url)
    flowPic.value = url;

    // if (data.code === 200) {
    //   uni.showToast({
    //     title: '获取图形验证码成功',
    //     icon: 'success'
    //   })
    // } else {
    //   uni.showToast({
    //     title: data.msg || '获取图形验证码失败',
    //     icon: 'none'
    //   })
    // }
  }).catch(err => {
    console.error('获取图形验证码失败:', err)
    uni.showToast({
      title: '获取图形验证码失败，请稍后重试',
      icon: 'none'
    })
  })
}

// 刷新图形验证码
const refreshCaptcha = () => {
  getImgCheckCode()
  // TODO: 调用接口获取图形验证码
  // 这里使用随机文本作为占位符，实际应该从接口获取图片或base64
  captchaText.value = generateCaptchaText()
  captchaCode.value = ''
  console.log('刷新验证码:', captchaText.value)
}

// 发送短信验证码
const sendSmsCode = () => {
  // 验证手机号
  // if (!phoneNumber.value || phoneNumber.value.includes('*')) {
  //   uni.showToast({
  //     title: '手机号不可用',
  //     icon: 'none'
  //   })
  //   return
  // }
  
  // 验证图形验证码
  if (!captchaCode.value) {
    uni.showToast({
      title: '请先输入图形验证码',
      icon: 'none'
    })
    return
  }

  sendUserCheckSmsCode()
  
  // TODO: 调用接口发送短信验证码
  console.log('发送短信验证码，图形验证码:', captchaCode.value)
  
  // 开始倒计时
  smsDisabled.value = true
  smsCountdown = 60
  
  smsTimer = setInterval(() => {
    smsCountdown--
    smsBtnText.value = `${smsCountdown}秒后重试`
    
    if (smsCountdown <= 0) {
      clearInterval(smsTimer)
      smsDisabled.value = false
      smsBtnText.value = '获取验证码'
    }
  }, 1000)
  
  uni.showToast({
    title: '验证码已发送',
    icon: 'success'
  })

}

const handleQuerys = () =>{
  userIDCheck()
}

// 查询
const handleQuery = () => {
  // 验证姓名
  if (!name.value || !name.value.trim()) {
    uni.showToast({
      title: '请输入姓名',
      icon: 'none'
    })
    return
  }
  
  // 验证身份证
  if (!idCard.value || !idCard.value.trim()) {
    uni.showToast({
      title: '请输入身份证',
      icon: 'none'
    })
    return
  }
  
  // 验证身份证格式
  const idCardPattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (!idCardPattern.test(idCard.value)) {
    uni.showToast({
      title: '身份证格式不正确',
      icon: 'none'
    })
    return
  }
  
  // 验证图形验证码
  if (!captchaCode.value || !captchaCode.value.trim()) {
    uni.showToast({
      title: '请输入图形验证码',
      icon: 'none'
    })
    return
  }
  
  // 验证短信验证码
  if (!smsCode.value || !smsCode.value.trim()) {
    uni.showToast({
      title: '请输入短信验证码',
      icon: 'none'
    })
    return
  }
  
  // // 验证成功后，调用查询接口
  // const verifyParams = {
  //   phoneNumber: phoneNumber.value,
  //   name: name.value,
  //   idCard: idCard.value,
  //   captchaCode: captchaCode.value,
  //   smsCode: smsCode.value
  // }
  
  // console.log('身份验证参数:', verifyParams)
  // console.log('查询参数:', queryParams.value)
  
  // // TODO: 调用身份验证接口，验证成功后调用查询接口
  // uni.showToast({
  //   title: '验证成功',
  //   icon: 'success'
  // })

    api.userIDCheck({
    // phone: phoneNumber.value,
    userName: name.value,
    idCardNum: idCard.value,
    imgCheckCode: captchaCode.value,
    smsCheckCode: smsCode.value
  }).then(res => {
    // const data = res.data
    console.log('身份验证:', JSON.stringify(res))
    if (res.code === 200) {
      uni.showToast({
        title: '身份验证成功',
        icon: 'success'
      })

        // 验证成功后，如果有查询参数，跳转到对应的详单页面
  // if (queryParams.value) {
    const serviceType = queryParams.value.serviceType
    const queryPhoneNumber = queryParams.value.phoneNumber || phoneNumber.value
    const selectedMonth = queryParams.value.selectedMonth || '2025年10月'
    const startDate = queryParams.value.startDate || '2025-10-01'
    const endDate = queryParams.value.endDate || '2025-10-31'
    
    const queryPeriod = queryParams.value.queryPeriod || '按按月查询'

    console.log('查询参数:', queryParams.value)
    
    // 根据服务类型跳转到不同的详单页面
    let targetPage = ''
    switch (serviceType) {
      case '流量':
        targetPage = '/pages/traffic-detail/traffic-detail'
        break
      case '语音':
        targetPage = '/pages/voice-detail/voice-detail'
        break
      case '短彩信':
        targetPage = '/pages/sms-detail/sms-detail'
        break
      case '增值服务':
        targetPage = '/pages/value-added-detail/value-added-detail'
        break
      default:
        targetPage = '/pages/traffic-detail/traffic-detail'
    }

    // 添加查询时间范围参数 // '按月查询', '按日查询'
    if (queryPeriod === '按月查询') {
      targetPage += `?phoneNumber=${encodeURIComponent(queryPhoneNumber)}&selectedMonth=${encodeURIComponent(selectedMonth)}&queryPeriod=${encodeURIComponent(queryPeriod)}`
    }else if (queryPeriod === '按日查询') {
      targetPage += `?phoneNumber=${encodeURIComponent(queryPhoneNumber)}&startDate=${encodeURIComponent(startDate)}&endDate=${encodeURIComponent(endDate)}&queryPeriod=${encodeURIComponent(queryPeriod)}`
    }
    
    // 跳转到对应的详单页面
    setTimeout(() => {
      uni.redirectTo({

        url: targetPage,
        success: () => {
          console.log('跳转到详单页面成功:', targetPage)
        },
        fail: (err) => {
          console.error('跳转失败:', err)
          uni.showToast({
            title: '跳转失败',
            icon: 'none'
          })
        }
      })
    }, 1500)
  // } else {
  //   // 没有查询参数，直接返回
  //   setTimeout(() => {
  //     uni.navigateBack()
  //   }, 1500)
  // }

    } else {
      uni.showToast({
        title: data.msg || '身份验证失败',
        icon: 'none'
      })
    }
  }).catch(err => {
    console.error('身份验证失败:', err)
    uni.showToast({
      title: '身份验证失败，请稍后重试',
      icon: 'none'
    })
  })
  

}
</script>

<style scoped>
.auth-page {
   
  position: relative;
  z-index: 1;
}

.page-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: -1;
  pointer-events: none;
  object-fit: cover;
}

.gradient-bg {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  pointer-events: none;
  backdrop-filter: blur(40rpx);
  background: rgba(255, 255, 255, 0.8);
}

.page-content {
  position: relative;
  z-index: 2;
  padding: 32rpx;
  padding-bottom: 40rpx;
}

/* 白色卡片容器 */
.form-card {
  border-radius: 16rpx;
  padding: 40rpx 32rpx;
  margin-bottom: 32rpx;
  /* background: rgba(255, 255, 255, 1); */
}

.form-item {
  margin-bottom: 40rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  color: rgba(51, 51, 51, 1);
  font-family: HarmonyOS Sans SC;
  font-size: 28rpx;
  font-weight: 400;
  line-height: 32rpx;
  margin-bottom: 16rpx;
  display: block;
}

.form-input-wrapper {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.form-input {
  flex: 1;
  height: 80rpx;
  padding: 0 24rpx;
  border: 2rpx solid rgba(204, 204, 204, 1);
  border-radius: 16rpx;
  font-family: HarmonyOS Sans SC;
  font-size: 28rpx;
  font-weight: 400;
  line-height: 80rpx;
  color: rgba(51, 51, 51, 1);
  /* background: rgba(255, 255, 255, 1); */
}

.form-input::placeholder {
  color: rgba(153, 153, 153, 1);
}

.form-input[disabled] {
  /* background: rgba(248, 248, 248, 1); */
  color: rgba(153, 153, 153, 1);
}

.captcha-input {
  flex: 1;
}

.captcha-image-wrapper {
  width: 200rpx;
  height: 80rpx;
  flex-shrink: 0;
  border: 2rpx solid rgba(204, 204, 204, 1);
  border-radius: 16rpx;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(248, 248, 248, 1);
  cursor: pointer;
  position: relative;
}

.captcha-text {
  font-family: 'Arial', sans-serif;
  font-size: 32rpx;
  font-weight: bold;
  color: rgba(78, 138, 254, 1);
  letter-spacing: 8rpx;
  user-select: none;
  transform: rotate(-5deg);
}

.sms-input {
  flex: 1;
}

.sms-btn {
  width: 180rpx;
  height: 80rpx;
  background: rgba(78, 138, 254, 1);
  color: rgba(255, 255, 255, 1);
  border-radius: 8rpx;
  font-family: HarmonyOS Sans SC;
  font-size: 28rpx;
  font-weight: 400;
  line-height: 80rpx;
  text-align: center;
  border: none;
  padding: 0;
  flex-shrink: 0;
  white-space: nowrap;
}

.sms-btn[disabled] {
  background: rgba(204, 204, 204, 1);
  color: rgba(255, 255, 255, 1);
}

/* 提示文字 */
.tip-text {
  text-align: center;
  margin-bottom: 40rpx;
}

.tip-text text {
  color: rgba(153, 153, 153, 1);
  font-family: HarmonyOS Sans SC;
  font-size: 24rpx;
  font-weight: 400;
  line-height: 28rpx;
}

/* 查询按钮 */
.query-btn {
  width: 100%;
  height: 80rpx;
  background: rgba(78, 138, 254, 1);
  color: rgba(255, 255, 255, 1);
  border-radius: 44rpx;
  font-family: HarmonyOS Sans SC;
  font-size: 32rpx;
  font-weight: 500;
  line-height: 80rpx;
  text-align: center;
  border: none;
  padding: 0;
  box-shadow: 0px 4rpx 12rpx rgba(78, 138, 254, 0.3);
}

.query-btn::after {
  border: none;
}

.query-btn:active {
  opacity: 0.8;
}
.form-tip{
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 32rpx;
}
</style>
